//
//  UIImage+Extension.swift
//  globalcarbusiness
//
//  Created by dongzhenyu on 2017/8/17.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import Foundation

public extension UIImage {
    
    public class func image(withColor color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
        if size.width <= 0 || size.height <= 0 {
            return self.init()
        }
        
        UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
        color.setFill()
        UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            return self.init()
        }
        UIGraphicsEndImageContext()
        guard let cgImage = image.cgImage else {
            return self.init()
        }
        return self.init(cgImage: cgImage)
    }
    
    // MARK: - 裁剪图片正中心区域
    public func centerImage() -> UIImage {
        let scale: CGFloat = self.scale
        let originWidth: CGFloat = self.size.width * scale
        let originHeight: CGFloat = self.size.height * scale
        
        // 裁剪图片正中区域
        let cropW: CGFloat = min(originWidth, originHeight)
        let cropX: CGFloat = ((originWidth - originHeight) > 0.0) ? (originWidth - originHeight) * 0.5 : 0.0
        let cropY: CGFloat = ((originHeight - originWidth) > 0.0) ? (originHeight - originWidth) * 0.5 : 0.0
        let cropRect: CGRect = CGRect(x: cropX, y: cropY, width: cropW, height: cropW)
        
        let cropImage = self.cgImage?.cropping(to: cropRect)
        if let cropImage = cropImage {
            let centerImage: UIImage = UIImage.init(cgImage: cropImage, scale: scale, orientation: self.imageOrientation)
            return centerImage
        } else {
            return self
        }
    }
    
    // MARK: - 裁剪成圆形图片
    public func circleImage() -> UIImage {
        let image = self.centerImage()
        
        UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
        let context = UIGraphicsGetCurrentContext()
        context!.setShouldAntialias(true)
        context!.setAllowsAntialiasing(true)
        
        let rect = CGRect(origin: .zero, size: image.size)
        context!.addEllipse(in: rect)
        context!.clip()
        image.draw(in: rect)
        
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        if let newImage = newImage {
            return newImage
        } else {
            return self
        }
    }
}
